package com.itcast.cn.request;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 中文乱码问题
 *      post请求：request.setCharacterEncoding(StandardCharsets.UTF_8.displayName());
 *      get请求/post请求：
 *          1. 先编码(和tomcat的编码一致), 获取字节数组
 *          2. 再以UTF-8解码 字节数组
 *
 * @author hyatt
 * @version 1.0
 */
@WebServlet("/request3")
public class RequestTest3 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        System.out.println("乱码前：" + username);
        username = new String(username.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
        System.out.println("解决乱码后：" + username);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // post请求可以直接设置字符集的方式解决
//        request.setCharacterEncoding(StandardCharsets.UTF_8.displayName());
//        String username = request.getParameter("username");
//        System.out.println("解决乱码后：" + username);
        this.doGet(request, response);
    }
}
